package com.fastbee.data.service.impl;

import com.fastbee.common.enums.DeviceStatus;
import com.fastbee.common.utils.DateUtils;
import com.fastbee.iot.domain.Device;
import com.fastbee.iot.service.IDeviceService;
import com.fastbee.iot.service.cache.IDeviceCache;
import com.fastbee.mqtt.manager.MqttRemoteManager;
import com.fastbee.sip.domain.SipDevice;
import com.fastbee.sip.domain.SipDeviceChannel;
import com.fastbee.sip.enums.DeviceChannelStatus;
import com.fastbee.sip.mapper.SipDeviceChannelMapper;
import com.fastbee.sip.mapper.SipDeviceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author gsb
 * @date 2023/2/20 17:13
 */
@Component
@Slf4j
public class DeviceJob {

    @Resource
    private IDeviceCache deviceCache;
    @Resource
    private IDeviceService deviceService;
    @Resource
    private MqttRemoteManager remoteManager;

    @Autowired
    private SipDeviceMapper sipDeviceMapper;

    @Autowired
    private SipDeviceChannelMapper sipDeviceChannelMapper;

    /**
     * 设备定时任务,更新超时设备状态
     */
    public void timingUpdateDeviceStatusStatus(){
        try {
            log.info("=>设备状态定时任务:" + DateUtils.getTimestamp());
            List<String> expiredDevice = deviceCache.removeExpiredDevice();
            deviceService.batchChangeStatus(expiredDevice, DeviceStatus.OFFLINE);
            for (String s : expiredDevice) {
                remoteManager.pushDeviceStatus(-1L,s,DeviceStatus.OFFLINE);
            }
        }catch (Exception e){
            log.warn("=>批量更新设备状态异常",e);
        }
    }

    public void updateSipDeviceOnlineStatus(Integer timeout) {
        List<SipDevice> devs = sipDeviceMapper.selectOfflineSipDevice(timeout);
        devs.forEach(item -> {
            if (!Objects.equals(item.getDeviceSipId(), "")) {
                //更新iot设备状态
                Device dev = deviceService.selectDeviceBySerialNumber(item.getDeviceSipId());
                if (dev != null && dev.getStatus() == 3) {
                    log.warn("定时任务：=>设备:{} 已经下线，设备超过{}秒没上线！",item.getDeviceSipId(),timeout);
                    dev.setStatus(4);
                    deviceService.updateDeviceStatusAndLocation(dev,"");
                }
                //更新通道状态
                List<SipDeviceChannel> channels = sipDeviceChannelMapper.selectSipDeviceChannelByDeviceSipId(item.getDeviceSipId());
                channels.forEach(citem -> {
                    citem.setStatus(DeviceChannelStatus.offline.getValue());
                    sipDeviceChannelMapper.updateSipDeviceChannel(citem);
                });
            }
        });
    }
}
